package jbrowser.gui.settings;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.ServiceLoader;
import jbrowser.services.ConfigurationService;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import jbrowser.gui.AbstractPage;
import jbrowser.services.ServiceRegistry;

public class SettingsPage extends AbstractPage implements ActionListener {

    ConfigurationService confService;

    @Override
    public void actionPerformed(ActionEvent e) {
        if ("Save".equals(e.getActionCommand())) {
            saveTree((TreeNode) treeServices.getModel().getRoot());
        }
    }

    private void saveTree(TreeNode root) {
        for (int i = 0; i < root.getChildCount(); i++) {
            saveTree(root.getChildAt(i));
        }
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) root;
        if (node.getUserObject() instanceof UserObject) {
            UserObject userObject = (UserObject) node.getUserObject();
            confService.setProperties(userObject.getName(), userObject.getProperties());
        }
    }

    public SettingsPage() {
        initComponents();
        btnSave.addActionListener(this);
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
        Iterator<ServiceRegistry> registries = ServiceLoader.load(ServiceRegistry.class).iterator();
        if (registries.hasNext()) {
            ServiceRegistry serviceRegistry = registries.next();
            Iterator<ConfigurationService> confServices = serviceRegistry.get(ConfigurationService.class).iterator();
            if (confServices.hasNext()) {
                confService = confServices.next();
                for (String confName : confService.getPropertyNames()) {
                    DefaultMutableTreeNode node = root;
                    String[] path = confName.split("\\.");
                    for (int i = 0; i < path.length - 1; i++) {
                        boolean exists = false;
                        for (int j = 0; j < node.getChildCount(); j++) {
                            DefaultMutableTreeNode child = (DefaultMutableTreeNode) node.getChildAt(i);
                            if (child.getUserObject().equals(path[i])) {
                                node = child;
                                exists = true;
                            }
                        }
                        if (!exists) {
                            DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(path[i]);
                            node.add(newNode);
                            node = newNode;
                        }
                    }
                    node.add(new DefaultMutableTreeNode(new UserObject(confName, confService)));
                }
            }
        }
        treeServices.setModel(new DefaultTreeModel(root));
        treeServices.addTreeSelectionListener(new TreeSelectionListener() {
            @Override
            public void valueChanged(TreeSelectionEvent e) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
                if (node.getUserObject() instanceof UserObject) {
                    UserObject userObject = (UserObject) node.getUserObject();
                    splSettings.setRightComponent(userObject.getEditor());
                }
            }
        });
    }

    @Override
    public String getTitle() {
        return "Settings";
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        btnSave = new javax.swing.JButton();
        splSettings = new javax.swing.JSplitPane();
        scrServicesTree = new javax.swing.JScrollPane();
        treeServices = new javax.swing.JTree();

        setLayout(new java.awt.GridBagLayout());

        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.insets = new java.awt.Insets(1, 1, 1, 1);
        add(btnSave, gridBagConstraints);

        splSettings.setDividerLocation(128);

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root");
        treeServices.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        treeServices.setRootVisible(false);
        scrServicesTree.setViewportView(treeServices);

        splSettings.setLeftComponent(scrServicesTree);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 0.1;
        gridBagConstraints.weighty = 0.1;
        gridBagConstraints.insets = new java.awt.Insets(1, 1, 1, 1);
        add(splSettings, gridBagConstraints);
    }// </editor-fold>//GEN-END:initComponents

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
    }//GEN-LAST:event_btnSaveActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnSave;
    private javax.swing.JScrollPane scrServicesTree;
    private javax.swing.JSplitPane splSettings;
    private javax.swing.JTree treeServices;
    // End of variables declaration//GEN-END:variables
}
